import numpy as np
import matplotlib
import matplotlib.pyplot as plt

# 设置字体为 SimHei
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

def drawcluster2(A, cluster, ncluster):
    """
    绘制聚类结果：
    - 正常簇：cluster[i] > 0，用不同颜色的实心圆表示
    - 噪声点：cluster[i] <= 0，用黑色小点表示
    参数:
        A: numpy.ndarray, shape (N,2)，待绘制数据
        cluster: array-like of length N，簇标签（<=0 表示噪声）
        ncluster: int，总簇数，用于 colormap
    """
    print("绘画当前聚类结果...")
    A = np.asarray(A)
    n, d = A.shape
    assert d >= 2, '只支持 2D 数据绘图'
    assert len(cluster) == n, 'cluster 长度必须与 A 的行数一致'
    assert all(0 <= c <= ncluster for c in cluster if c > 0), 'cluster 值超出范围'

    # 使用 HSV colormap，离散 ncluster 个颜色
    print("使用 HSV colormap，离散 ncluster 个颜色,总共", ncluster+1, "种颜色")
    cmap = plt.get_cmap('hsv', ncluster+1)

    fig, ax = plt.subplots()
    valid_point = 0
    for i in range(n):
        x, y = A[i, 0], A[i, 1]
        label = cluster[i]
        # print("点坐标：", x, y, "标签：", label)
        if label > 0:
            valid_point += 1
            # 簇标签从 1 到 ncluster，对应 colormap 下标 0~ncluster-1
            color = cmap(label - 1)
            # print("点坐标：", x, y, "标签：", label, "颜色：", label - 1)
            ax.plot(
                x, y,
                'o',
                markersize=3,
                markerfacecolor=color,
                markeredgecolor=color
            )
        else:
            # 噪声点
            # print("点坐标：", x, y, "标签：", label, "颜色：", "黑色")
            ax.plot(
                x, y,
                'k.',  # 黑色小点
                markersize=16
            )
    # 调整坐标轴位置
    print("有效点个数：", valid_point)
    print("总点个数：", n)
    ax.set_position([0.05, 0.05, 0.9, 0.9])
    plt.show()
